package com.gong.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gong.reggie.common.CustomException;
import com.gong.reggie.dto.SetmealDto;
import com.gong.reggie.entity.Setmeal;
import com.gong.reggie.entity.SetmealDish;
import com.gong.reggie.mapper.SetmealDishMapper;
import com.gong.reggie.mapper.SetmealMapper;

import com.gong.reggie.service.SetmealDishService;
import com.gong.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper,Setmeal> implements SetmealService {
    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDto
     */
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealMapper setmealMapper;




    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishes);
    }
    /**
     * 删除套餐，同时需要删除套餐和菜品的关联关系
     * @param
     */

    @Override
    @Transactional
    public void deleteById(List<Long> ids) {
        //判断当前要删除的套餐是否处于售卖状态 ,如果是 不允许删除,否则删除.
        //select count(*) from setmeal where id in (1,2,3)
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();

        qw.in(Setmeal::getId,ids);
        qw.eq(Setmeal::getStatus,1);
        Integer count = setmealMapper.selectCount(qw);
        if(count>0){//当前套餐存在售卖状态,不可删除
            throw  new CustomException("当前套餐存在售卖状态,不可删除");
        }


        //删除套餐: delete from setmeal where id in (1,2,3)
        setmealMapper.deleteBatchIds(ids);

        //删除套餐对应的菜品数据: delete from setmeal_dish where setmeal_id in(1,2,3)
        LambdaQueryWrapper<SetmealDish> qw1 = new LambdaQueryWrapper<>();
        qw1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(qw1);

    }

    @Override
    public void updateSetmeal(Integer status, List<Long> ids) {

    }

    @Override
    public List<Setmeal> listByCategoryIdAndStatus(Long categoryId, Integer status) {
        return null;
    }
}
